import os, threading, requests, queue

from WSModule import WSModule
from WSThread import WSThread
from DafsThread import DafsThread
from WSJob import WSJob
from WSResult import WSResult
from WSOption import WSOption
from WSOptionGeneratorDict import WSOptionGeneratorDict
from WSCounter import WSCounter
#TODO проверка в обоих дафсах на наличие msymbol

class DafsDict(WSModule):
    log_path = os.getcwd() + '/results/dafs-result'
    options = {"threads": WSOption("threads", "Threads count, default 10", 10, False, ['-t', '--threads']),
               "url": WSOption("url", "Target URL", "", True, ['-u', '--url']),
               "dict": WSOption("dict", "Dictionary for search", "", True, ['-d', '--dict']),
               "msymbol": WSOption("msymbol", "Symbol of objects position in target URL (default №)",
                   "№", False, ['--msymbol']),
               "method": WSOption("method", "Request method (default - HEAD)",
                   "HEAD", False, ['--method']),
               }
    def __init__(self, kernel): #TODO не надо вынести в WSModule?
        super().__init__(kernel)
        for option_name in self.options:
            self.options[option_name].module = self
        self.result = WSResult()

    def run(self):
        if self.options['url'].value.find(self.options['msymbol'].value) == -1:
            exit(print("Symbol of object position ({0}) not found in URL ({1}) ".format(self.options['msymbol'].value,
                                                                                        self.options['url'].value)))

        q = queue.Queue()
        fh = open(self.options['dict'].value)
        while True:
            line = fh.readline()
            if not line: break
            if not line.strip(): continue
            q.put(line.strip())

        counter = WSCounter(5, 150)

        for i in range(self.options['threads'].value):
            worker = DafsThread(q, self.result, self.options['url'].value, self.options['method'].value, self.options['msymbol'].value, counter)
            worker.daemon = True
            worker.start()

        q.join()

    def help(self):
        return "Dafs help"

    def finished(self):
        return self.kernel.finished()
